<template>
  <view class="container">
    <view class="example">
      <uni-forms ref="form" :model="form" labelWidth="80px">
        <uni-forms-item label="籍贯" name="nativePlace">
          <picker
            mode="multiSelector"
            :range="[provinceList, cityList, districtList]"
            :value="[
              selectedProvinceIndex,
              selectedCityIndex,
              selectedDistrictIndex,
            ]"
            @change="handleChange"
            @columnchange="pickerColumnChange"
          >
            <view class="picker">
              {{ selectedValues.join(" ") }}
            </view>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="联系电话" name="phone">
          <uni-easyinput v-model="form.phone" placeholder="请输入联系电话" />
        </uni-forms-item>
        <uni-forms-item label="电子邮箱" name="mail">
          <uni-easyinput v-model="form.mail" placeholder="请输入邮箱" />
        </uni-forms-item>
        <uni-forms-item label="联系人" name="urgentContact">
          <uni-easyinput :maxlength="lxrLenght"
            v-model="form.urgentContact"
            placeholder="请输入联系人"
          />
        </uni-forms-item>
        <uni-forms-item label="联系人电话" name="urgentContactPhone">
          <uni-easyinput v-model="form.urgentContactPhone" placeholder="请输入联系人电话" />
        </uni-forms-item>
        <uni-forms-item label="家庭住址" name="homeAddress">
          <uni-easyinput
            v-model="form.homeAddress"
            placeholder="请输入家庭住址"
          />
        </uni-forms-item>
      </uni-forms>
      <button type="primary" @click="submit">提交</button>
    </view>
  </view>
</template>

<script>
import { getInduction, updateInduction } from "@/api/hrm/staff/induction";
import { queryAll } from "@/api/area";
import isHaveBug from "../../../utils/bug";

export default {
  data() {
    return {
      form: {
        nativePlace: "",
        phone: "",
        mail: "",
        urgentContact: "",
        lxrPhone: "",
        homeAddress: "",
      },
	  lxrLenght: 64,
      provinces: [],
      selectedProvinceIndex: 0,
      selectedCityIndex: 0,
      selectedDistrictIndex: 0,
      selectedValues: ["请选择省", "请选择市", "请选择区"],

      rules: {
        nativePlace: {
          rules: [
            {
              required: true,
              errorMessage: "籍贯不能为空",
            },
          ],
        },
        phone: {
          rules: [
            {
              required: true,
              errorMessage: "手机号码不能为空",
            },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              errorMessage: "请输入正确的手机号码",
            },
          ],
        },
        mail: {
          rules: [
            {
              required: true,
              errorMessage: "邮箱地址不能为空",
            },
            {
              format: "email",
              errorMessage: "请输入正确的邮箱地址",
            },
          ],
        },
        urgentContact: {
          rules: [
            {
              required: true,
              errorMessage: "联系人不能为空",
            },
            // {
            //   maxLength: 64,
            //   errorMessage: "联系人字符长度要求64位（含）以内",
            // },
          ],
        },
		urgentContactPhone: {
			rules: [
			  {
			    required: true,
			    errorMessage: "联系人电话不能为空",
			  },
			  {
			    maxLength: 100,
			    errorMessage: "联系人电话字符长度要求100位（含）以内",
			  },
			],
		},
        homeAddress: {
          rules: [
            {
              required: true,
              errorMessage: "家庭住址不能为空",
            },
            {
              maxLength: 60,
              errorMessage: "家庭住址字符长度要求60位（含）以内",
            },
          ],
        },
      },
    };
  },
  onLoad() {
    Promise.all([queryAll()])
      .then(([response]) => {
        this.provinces = response.data;
        // 在字典数据加载完成后调用 getUser
        this.getUser();
      })
      .catch((error) => {
        console.error("Error loading dictionary data:", error);
      });
	  
	  if (isHaveBug("HR-APP-008")){
		  this.lxrLenght = -1
	  }
  },
  onReady() {
    this.$refs.form.setRules(this.rules);
  },
  computed: {
    provinceList() {
      return this.provinces.map((p) => p.name);
    },
    cityList() {
      const selectedProvince = this.provinces[this.selectedProvinceIndex];
      return selectedProvince && selectedProvince.areas
        ? selectedProvince.areas.map((c) => c.name)
        : [];
    },
    districtList() {
      const selectedCity =
        this.provinces[this.selectedProvinceIndex]?.areas[
          this.selectedCityIndex
        ];
      return selectedCity && selectedCity.areas
        ? selectedCity.areas.map((d) => d.name)
        : [];
    },
  },
  methods: {
    pickerColumnChange(e) {
      const column = e.detail.column;
      const index = e.detail.value;

      if (column === 0) {
        // 当选择省份时，重置市和区的索引
        this.selectedProvinceIndex = index;
        this.selectedCityIndex = 0;
        this.selectedDistrictIndex = 0;
      } else if (column === 1) {
        // 当选择市时，重置区的索引
        this.selectedCityIndex = index;
        this.selectedDistrictIndex = 0;
      } else if (column === 2) {
        this.selectedDistrictIndex = index;
      }

      // 更新显示的选项
      this.updateSelectedValues();
    },
    updateSelectedValues() {
      const selectedProvince = this.provinces[this.selectedProvinceIndex] || {};
      const selectedCity = selectedProvince.areas
        ? selectedProvince.areas[this.selectedCityIndex]
        : {};
      const selectedDistrict = selectedCity.areas
        ? selectedCity.areas[this.selectedDistrictIndex]
        : {};

      this.selectedValues = [
        selectedProvince.name || "请选择省",
        selectedCity.name || "请选择市",
        selectedDistrict.name || "请选择区",
      ];

      // 保存选定的值到 nativePlace 中
      this.form.nativePlace = this.selectedValues.join(" ");
    },
    handleChange(e) {
      const [provinceIndex, cityIndex, districtIndex] = e.detail.value;
      this.selectedProvinceIndex = provinceIndex;
      this.selectedCityIndex = cityIndex;
      this.selectedDistrictIndex = districtIndex;

      this.updateSelectedValues();
    },

    getUser() {
      let tokenList = uni.getStorageSync("storage_data") || {};
      let id = tokenList.vuex_id;
      getInduction(id)
        .then((response) => {
          this.form = response.data;
          // 初始化 picker 选项
          this.initPicker();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    submit(ref) {
      this.$refs.form.validate().then((res) => {
        updateInduction(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
        });
      });
    },

    initPicker() {
      // 如果 nativePlace 为空或者未定义，则直接返回
      if (!this.form.nativePlace) {
        return;
      }
      // 初始化省、市、区索引和选定值
      const nativePlace = this.form.nativePlace.split(" ");
      if (nativePlace.length === 3) {
        const [provinceName, cityName, districtName] = nativePlace;
        this.selectedProvinceIndex = this.provinces.findIndex(
          (p) => p.name === provinceName
        );
        const selectedProvince = this.provinces[this.selectedProvinceIndex];
        this.selectedCityIndex = selectedProvince.areas.findIndex(
          (c) => c.name === cityName
        );
        const selectedCity = selectedProvince.areas[this.selectedCityIndex];
        this.selectedDistrictIndex = selectedCity.areas.findIndex(
          (d) => d.name === districtName
        );

        this.updateSelectedValues();
      }
    },
    submit() {
      this.$refs.form.validate().then(() => {
        updateInduction(this.form).then(() => {
          this.$modal.msgSuccess("修改成功");
        });
      });
    },
  },
};
</script>

<style lang="scss">
.picker {
  padding: 15px;
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 20px;
  text-align: center;
}

page {
  background-color: #ffffff;
}

.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
}
</style>
